// pages/volunteer/register.js
Page({
  data: {
    formData: {
      name: '',
      idCard: '',
      phone: '',
      age: '',
      gender: '',
      email: '',
      wechat: '',
      address: '',
      occupation: '',
      education: '',
      serviceTime: [],
      serviceType: [],
      emergencyName: '',
      emergencyRelation: '',
      emergencyPhone: ''
    },
    educationLevels: ['请选择', '小学', '初中', '高中', '大专', '本科', '硕士', '博士'],
    educationIndex: 0,
    serviceTimes: [
      { value: 'weekday', label: '工作日', checked: false },
      { value: 'weekend', label: '周末', checked: false },
      { value: 'holiday', label: '节假日', checked: false },
      { value: 'flexible', label: '灵活时间', checked: false }
    ],
    serviceTypes: [
      { value: 'promotion', label: '宣传推广', checked: false },
      { value: 'service', label: '志愿服务', checked: false },
      { value: 'support', label: '后勤支持', checked: false },
      { value: 'coordination', label: '活动协调', checked: false }
    ],
    agreements: {
      volunteer: false,
      privacy: false
    },
    canSubmit: false,
    isSubmitting: false,
    showSuccessModal: false
  },

  onLoad: function (options) {
    // 页面加载时的初始化
  },

  // 输入框变化处理
  onInputChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    });
    
    this.checkFormValidity();
  },

  // 性别选择处理
  onGenderChange: function (e) {
    this.setData({
      'formData.gender': e.detail.value
    });
    this.checkFormValidity();
  },

  // 教育程度选择处理
  onEducationChange: function (e) {
    const index = e.detail.value;
    this.setData({
      educationIndex: index,
      'formData.education': this.data.educationLevels[index]
    });
  },

  // 服务时间选择处理
  onServiceTimeChange: function (e) {
    const values = e.detail.value;
    const serviceTimes = this.data.serviceTimes.map(item => ({
      ...item,
      checked: values.includes(item.value)
    }));
    
    this.setData({
      serviceTimes: serviceTimes,
      'formData.serviceTime': values
    });
  },

  // 服务类型选择处理
  onServiceTypeChange: function (e) {
    const values = e.detail.value;
    const serviceTypes = this.data.serviceTypes.map(item => ({
      ...item,
      checked: values.includes(item.value)
    }));
    
    this.setData({
      serviceTypes: serviceTypes,
      'formData.serviceType': values
    });
  },

  // 协议同意处理
  onAgreementChange: function (e) {
    const type = e.currentTarget.dataset.type;
    const checked = e.detail.value;
    
    this.setData({
      [`agreements.${type}`]: checked
    });
    
    this.checkFormValidity();
  },

  // 检查表单有效性
  checkFormValidity: function () {
    const { formData, agreements } = this.data;
    
    // 检查必填字段
    const requiredFields = [
      formData.name,
      formData.idCard,
      formData.phone,
      formData.age,
      formData.gender,
      formData.address,
      formData.emergencyName,
      formData.emergencyRelation,
      formData.emergencyPhone
    ];
    
    const isRequiredValid = requiredFields.every(field => field && field.trim() !== '');
    
    // 检查协议同意
    const isAgreementValid = agreements.volunteer && agreements.privacy;
    
    // 检查手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    const isPhoneValid = phoneRegex.test(formData.phone);
    
    // 检查身份证号格式
    const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    const isIdCardValid = idCardRegex.test(formData.idCard);
    
    // 检查年龄
    const age = parseInt(formData.age);
    const isAgeValid = age >= 18 && age <= 70;
    
    this.setData({
      canSubmit: isRequiredValid && isAgreementValid && isPhoneValid && isIdCardValid && isAgeValid
    });
  },

  // 表单提交
  submitForm: function (e) {
    if (!this.data.canSubmit) {
      wx.showToast({
        title: '请完善必填信息',
        icon: 'none'
      });
      return;
    }

    this.setData({
      isSubmitting: true
    });

    // 模拟提交过程
    setTimeout(() => {
      // 保存到本地存储
      const registrations = wx.getStorageSync('volunteerRegistrations') || [];
      const newRegistration = {
        ...this.data.formData,
        id: Date.now().toString(),
        status: 'pending',
        submitTime: new Date().toISOString()
      };
      
      registrations.push(newRegistration);
      wx.setStorageSync('volunteerRegistrations', registrations);

      this.setData({
        isSubmitting: false,
        showSuccessModal: true
      });

      // 重置表单
      this.resetForm();
    }, 2000);
  },

  // 重置表单
  resetForm: function () {
    this.setData({
      formData: {
        name: '',
        idCard: '',
        phone: '',
        age: '',
        gender: '',
        email: '',
        wechat: '',
        address: '',
        occupation: '',
        education: '',
        serviceTime: [],
        serviceType: [],
        emergencyName: '',
        emergencyRelation: '',
        emergencyPhone: ''
      },
      educationIndex: 0,
      serviceTimes: this.data.serviceTimes.map(item => ({ ...item, checked: false })),
      serviceTypes: this.data.serviceTypes.map(item => ({ ...item, checked: false })),
      agreements: {
        volunteer: false,
        privacy: false
      },
      canSubmit: false
    });
  },

  // 关闭成功弹窗
  closeSuccessModal: function () {
    this.setData({
      showSuccessModal: false
    });
    
    // 返回上一页
    wx.navigateBack();
  },

  // 分享
  onShareAppMessage: function () {
    return {
      title: '志愿者注册 - 爱道・遗体捐献服务',
      path: '/pages/volunteer/register'
    };
  }
});